package pers.xiaoliang.concurrency.example.count;

import lombok.extern.slf4j.Slf4j;
import pers.xiaoliang.concurrency.annotation.ThreadSafe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @version v1.0
 * @description: 计数器例子2 使用AtomicIntegerFieldUpdater
 * @author: xiaoliang.liu
 * @date: 2018/7/26 21:31
 */
@Slf4j
@ThreadSafe
public class CountExample5 {

    private static AtomicBoolean isHappend = new AtomicBoolean(false);

    /**
     * 线程数量(模拟并发数)
     */
    private static int threadTotal = 200;
    /**
     * 请求次数
     */
    private static int clientTotal = 5000;


    public static void main(String[] args) throws InterruptedException {
        // 获得线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 信号量
        final Semaphore semaphore = new Semaphore(threadTotal);

        // 闭锁
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    test();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println(e);
                }

                // 闭锁计数器减一
                countDownLatch.countDown();
            });
        }

        // 阻塞
        countDownLatch.await();

        // 关闭线程池
        executorService.shutdown();
        System.out.println(isHappend.get());
        executorService.shutdown();

    }
    private static void test() {
        if (isHappend.compareAndSet(false, true)) {
            log.info("execute");
        }
    }

}
